import cv2 as cv
import copy
import numpy as np
img_rice_path = "rice.png"
img_rice = cv.imread(img_rice_path)
rice_gray = cv.cvtColor(img_rice, cv.COLOR_BGR2GRAY)
# 大津算法阈值化,局部阈值
bw = cv.adaptiveThreshold(rice_gray, 255, cv.ADAPTIVE_THRESH_MEAN_C,
                          cv.THRESH_BINARY, 101, 1)
# 全局阈值
#_, bw = cv.threshold(rice_gray, 0, 0xff, cv.THRESH_OTSU)
# 形态学去噪
element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)
seg = copy.deepcopy(bw)
#图像分割
bin, cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL,
                                  cv.CHAIN_APPROX_SIMPLE)

count = 0
area_sum = 0
length_sum = 0
length_list = []
for i in range(len(cnts), 0, -1):
    c = cnts[i - 1]
    # 求分割出来的面积
    area = cv.contourArea(c)

    # 小于10 认为是噪声
    if area < 10:
        continue
    count = count + 1
    area_sum = area_sum + area
    print("blob", i, " : ", area)
    (x, y), radius = cv.minEnclosingCircle(c)
    length = radius * 2
    length_sum = length_sum + length
    length_list.append(length)
    #求出包围矩形
    #x, y, w, h = cv.minAreaRect(c)
    x, y, w, h = cv.boundingRect(c)
    #画出矩形
    cv.rectangle(img_rice, (x, y), (x + w, y + h), (0, 0, 0xff), 1)
    cv.putText(img_rice, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5,
               (0, 0XFF, 0))
#print("area_sum: ", area_sum)
print("平均面积: ", format(round(area_sum / count, 2)))
length_avg = np.mean(length_list)
print("平均长度: ", length_avg)
length_var = np.var(length_list)
print("长度方差:", length_var)
length_std = np.std(length_list)
print("标准差：", length_std)
std3 = 3 * length_std
top = length_avg + std3
down = length_avg - std3
print("top:", top, "down:", down)
std_count = 0
for i in range(len(length_list), 0, -1):
    item = length_list[i - 1]
    if item > down or item < top:
        print("length:", item)
        std_count = std_count + 1
    else:
        print("----", item)
print("总数量：", count)
print("长度3标准差数量：", std_count)
cv.imshow("t", bw)
cv.imshow("t1", img_rice)
cv.waitKey()
cv.destroyAllWindows()
